package main

import (
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/v2/inner/uuid"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"mxshop-api/userop-web/global"
	"mxshop-api/userop-web/initialize"
	"mxshop-api/userop-web/utils"
	"mxshop-api/userop-web/utils/register/consul"
	"os"
	"os/signal"
	"syscall"
)

func main() {

	//1.初始化日志
	initialize.InitLogger()
	//2.初始化配置文件
	initialize.InitConfig()
	//3.初始化Routers
	Router := initialize.Routers()
	//4. 初始化 翻译
	if err := initialize.InitTrans("zh"); err != nil {
		panic(err)
	}
	//5. 初始化srv连接
	initialize.InitSrvConn()

	viper.AutomaticEnv() // 自动从环境变量获取值
	//如果是本地开发环境端口号固定,线上环境启动获取端口号
	debug := viper.GetBool(global.ServerConfig.Dev)
	if !debug {
		port, err := utils.GetFreePort()
		if err == nil {
			global.ServerConfig.Port = port //更改端口号
		}
	}
	consulInfo := global.ServerConfig.ConsulInfo
	serviceId, _ := uuid.NewV4()
	srvId := fmt.Sprintf("%s", serviceId)

	registerClient := consul.NewRegistryClient(consulInfo.Host, consulInfo.Port)
	err := registerClient.Register(global.ServerConfig.Host, global.ServerConfig.Port, global.ServerConfig.Name, global.ServerConfig.Tags, srvId)
	if err != nil {
		zap.S().Panic("服务注册失败：", err.Error())
	}
	//全局日志
	zap.S().Debugf("启动服务器, 端口: %d", global.ServerConfig.Port)

	go func() {
		if err := Router.Run(fmt.Sprintf(":%d", global.ServerConfig.Port)); err != nil {
			zap.S().Panic("启动失败:", err.Error())
		}
	}()
	//接收终止信号
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	if err = registerClient.DeRegister(srvId); err != nil {
		zap.S().Info("注销失败:", err.Error())
	} else {
		zap.S().Info("注销成功")
	}
}
